import logging

from google.appengine.ext import db
from google.appengine.api import memcache

class Activity(db.Model):
    """Some topic update.
    """
    owner = db.StringProperty() # activity belongs to this user
    title = db.StringProperty(multiline=True)
    content = db.TextProperty()
    updated = db.DateTimeProperty(auto_now_add=True)
    link = db.TextProperty()
    object_type = db.StringProperty()
    geopoint = db.StringProperty()
    
class Subscription(db.Model):
    user = db.StringProperty()
    ms_subscription_id = db.StringProperty()
    save_raw_feeds = db.BooleanProperty(default=False)

    @staticmethod
    def get_user_subscription(user_id):
        subscription = memcache.get(user_id)
        if subscription is not None:
            return subscription
        else:
            query = Subscription.gql("WHERE user = :user", user=user_id)
            subscription = query.get()
            if not memcache.set(user_id, subscription):
               logging.error("Memcache set failed for Subscription.")
            return subscription

    @staticmethod
    def get_subscription(subscription_id):
        query = Subscription.gql("WHERE ms_subscription_id = :ms_subscription_id", ms_subscription_id=subscription_id)
        return query.get()
    
    @staticmethod
    def delete_subscription(subscription_id):
        subscription = Subscription.get_subscription(subscription_id)
        memcache.delete(subscription.user)
        db.delete(subscription)
    
class RawFeed(db.Model):
    owner = db.StringProperty() # feed belongs to this user
    feed = db.TextProperty()
    updated = db.DateTimeProperty(auto_now_add=True)

    @staticmethod
    def get_raw_feed_count(user_id):
        query = RawFeed.gql("WHERE owner = :owner", owner=user_id)
        return query.count()

    @staticmethod
    def get_latest_feed(user_id):
        query = RawFeed.gql("WHERE owner = :owner ORDER BY updated DESC", owner=user_id)
        return query.get()

    @staticmethod
    def get_raw_feeds_from_datastore(user_id, count):
        query = RawFeed.gql("WHERE owner = :owner ORDER BY updated DESC", owner=user_id)
        return query.fetch(count)
